//小仓库:layout组件相关配置仓库
import { defineStore } from 'pinia'
import { getLocalStorage, setLocalStorage } from '@/utils/localStorage.ts'
import type { SettingType } from './types/type'
import store from '../index'
import { useDark, useToggle } from '@vueuse/core'
import { config } from '@/config'

const useStore = defineStore('SettingStore', {
  state: (): SettingType => {
    return {
      layoutConfig: getLocalStorage('layoutConfig'), // layout整体配置
      refsh: false, // 仓库这个属性用于控制刷新效果
    }
  },
  actions: {
    resetLayoutConfig() {
      // 存储配置
      type Key = keyof LayoutConfig
      Object.keys(config).forEach((key) => this.setLayoutProps(key as Key, config[key as Key]))
      this.layoutConfig = config
    },
    setLayoutProps<K extends keyof LayoutConfig>(key: K, value: LayoutConfig[K]) {
      this.layoutConfig[key] = value
      if (key === 'Theme') {
        // 设置菜单栏 主题色
        const el = document.documentElement
        const arr = [...el.classList]
        el.classList.remove(...arr)
        arr[0] = `theme-${this.layoutConfig.Theme}`
        el.classList.add(...arr)
      } else if (key === 'DarkMode') {
        // 设置暗黑模式
        const dark = useDark()
        dark.value = this.layoutConfig.DarkMode
        useToggle(dark)
      } else if (key === 'Grey') {
        // 设置灰色模式
        const el = document.documentElement
        if (this.layoutConfig.Grey) {
          el.classList.add('theme-grey')
        } else {
          el.classList.remove('theme-grey')
        }
      } else if (key === 'Weak') {
        // 设置弱色模式
        const el = document.documentElement
        if (this.layoutConfig.Weak) {
          el.classList.add('theme-weak')
        } else {
          el.classList.remove('theme-weak')
        }
      }
      setLocalStorage('layoutConfig', this.layoutConfig)
    },
  },
})

export function useSettingStore() {
  return useStore(store)
}
